import base64
import json
import pickle

from django.http import HttpResponseForbidden, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from carts.utils import merge_cart_cookie_to_redis
from goods.models import SKU


class CartsView(View):
    def post(self, request):
        dict = json.loads(request.body.decode())

        sku_id = dict.get('sku_id')
        count = dict.get('count')
        selected = dict.get('selected', True)

        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')

        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return HttpResponseForbidden('商品不存在')

        try:
            count = int(count)
        except Exception as e:
            return HttpResponseForbidden('参数count有误')

        if selected:

            if not isinstance(selected, bool):
                return HttpResponseForbidden('参数selected有误')

        if request.user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hincrby('carts_%s' % request.user.id,
                       sku_id,
                       count)

            if selected:
                pl.sadd('selected_%s' % request.user.id,
                        sku_id)
            pl.execute()

            return JsonResponse({
                'code': 0,
                'errmsg': '添加购物车成功'
            })
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))

            else:
                cart_dict = {}

            if sku_id in cart_dict:
                count += cart_dict[sku_id]['count']

            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response = JsonResponse({
                'code': 0,
                'errmsg': '添加购物车成功'
            })

            response.set_cookie('carts', cart_data)

            return response

    def get(self, request):

        user = request.user
        if user.is_authenticated:

            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            cart_dict = {}

            for sku_id, count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }

        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads((base64.b64decode(cookie_cart.encode())))
            else:
                cart_dict = {}

        sku_ids = cart_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count')
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })

    def put(self, request):

        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        if not all([sku_id, count]):
            return HttpResponseForbidden('缺少必传参数')

        try:
            sku = SKU.objects.get(id=sku_id)
            count = int(count)

        except Exception as e:
            return HttpResponseForbidden('商品sku_id不存在, count值不正确')

        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            pl.hset('carts_%s' % user.id,
                    sku_id,
                    count)

            if selected:
                pl.sadd('selected_%s' % user.id,
                        sku_id)
            else:
                pl.srem('selected_%s' % user.id,
                        sku_id)
            pl.execute()

            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected,
                'price': sku.price,
                'name': sku.name,
                'default_image_url': sku.default_image_url,
                'amount': sku.price * count,
            }
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': cart_sku
            })


        else:
            cookie_cart = request.COOKIES.get('carts')

            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
            cart_dict[sku_id] = {
                'count': count,
                'selected': selected
            }

            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
            cart_sku = {
                'id': sku_id,
                'count': count,
                'selected': selected
            }

            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok',
                'cart_sku': cart_sku
            })

            response.set_cookie('carts', cart_data)

            return response

    def delete(self, request):

        json_dict = json.loads(request.body.decode())

        sku_id = json_dict.get('sku_id')
        try:
            sku = SKU.objects.filter(id=sku_id)
        except Exception as e:
            return HttpResponseForbidden('返回的sku_id错误')

        user = request.user

        if user.is_authenticated:

            try:
                redis_conn = get_redis_connection('carts')

                redis_conn.hdel('carts_%s' % user.id, sku_id)

                redis_conn.srem('selected_%s' % user.id, sku_id)
            except Exception as e:
                return HttpResponseForbidden('连接数据库失败')
            return JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
        else:

            cookie_data = request.COOKIES.get('carts')

            if cookie_data:

                cart_dict = pickle.loads(base64.b64decode(cookie_data.encode()))
            else:
                cart_dict = {}

            response = JsonResponse({
                'code': 0,
                'errmsg': '删除购物车成功'
            })
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

            response.set_cookie('carts', cart_data)

            return response


class CartSelectAllView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get('selected', True)
        redis_conn = get_redis_connection('carts')

        user = request.user
        if selected:
            if not isinstance(selected, bool):
                return HttpResponseForbidden('selected无效')

        if user.is_authenticated:

            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)

            sku_ids = item_dict.keys()

            if selected:
                redis_conn.sadd('selected_%s' % user.id, *sku_ids)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_ids)

            return JsonResponse({
                'code': 0,
                'errmsg': '全选购物车成功过'
            })
        else:

            cookie_data = request.COOKIES.get('carts')
            response = JsonResponse({
                'code': 0,
                'errmsg': 'ok'
            })
            # 合并购物车
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)
            if cookie_data:
                cart_dict = pickle.loads(base64.b64decode(cookie_data.encode()))

                for sku_id in cart_dict.keys():
                    cart_dict[sku_id]['selected'] = selected
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()

                response.set_cookie('carts', cart_data)

            return response


class CartsSimpleView(View):
    def get(self, request):
        user = request.user
        if user.is_authenticated:

            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)

            cart_dict = {}

            for sku_id, count in item_dict.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in cart_selected
                }

        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads((base64.b64decode(cookie_cart.encode())))
            else:
                cart_dict = {}

        sku_ids = cart_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'selected': cart_dict.get(sku.id).get('selected'),
                'default_image_url': sku.default_image_url,
                'price': sku.price,
                'amount': sku.price * cart_dict.get(sku.id).get('count')
            })

        return JsonResponse({
            'code': 0,
            'errmsg': 'ok',
            'cart_skus': cart_skus
        })
